<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/21 0021
 * Time: 下午 2:22
 */
namespace app\lib\express;

/**
 * 快递鸟接口
 * Class Base
 * @package app\lib\express
 */
class Express{
    private $EBusinessID; //用户ID
    private $AppKey; //电商加密私钥
    private $ReqURL; //请求地址
    private $Sender_Name = '荆裕优选';
    private $Sender_Mobile = '13100663715';
    private $Sender_ProvinceName = '湖北省';
    private $Sender_CityName = '武汉市';
    private $Sender_ExpAreaName = '洪山区';
    private $Sender_Address = '光谷街30号';

    function __construct()
    {
        $this->EBusinessID = config('express.EBusinessID');
        $this->AppKey = config('express.AppKey');
        $this->ReqURL = config('express.ReqURL');
    }


    //电子面单
    public function submitEOrder(){
        
    }

    /**
     * Json方式 实时查询订单物流轨迹
     */
    public function getOrderTracesByJson($requestData){
        $ShipperCode = $requestData['ShipperCode'];
        $LogisticCode = $requestData['LogisticCode'];
        $requestData= "{'ShipperCode':'$ShipperCode','LogisticCode':'$LogisticCode'}";

        $datas = array(
            'EBusinessID' => $this->EBusinessID,
            'RequestType' => '1002',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, $this->AppKey);
        $result=$this->sendPost($this->ReqURL, $datas);

        //根据公司业务处理返回的信息......

        return json_decode($result,true);
    }

    /**
     * Json方式  物流信息订阅  （订阅之后如果快递轨迹有变化 快递鸟将推送物流轨迹信息到回调接口）
     */
    public function orderTracesSubByJson($requestData){
        $OrderCode = $requestData['OrderCode'];
        $ShipperCode = $requestData['ShipperCode'];
        $LogisticCode = $requestData['LogisticCode'];
        $ReceiverName = $requestData['ReceiverName'];
        $ReceiverMobile = $requestData['ReceiverMobile'];
        $ReceiverProvinceName = $requestData['ReceiverProvinceName'];
        $ReceiverCityName = $requestData['ReceiverCityName'];
        $ReceiverExpAreaName = $requestData['ReceiverExpAreaName'];
        $ReceiverAddress = $requestData['ReceiverAddress'];
        $requestData="{'OrderCode': '$OrderCode',".
            "'ShipperCode':'$ShipperCode',".
            "'LogisticCode':'$LogisticCode',".
            "'Sender':".
            "{".
            "'Name':'$this->Sender_Name','Mobile':'$this->Sender_Mobile','ProvinceName':'$this->Sender_ProvinceName','CityName':'$this->Sender_CityName','ExpAreaName':'$this->Sender_ExpAreaName','Address':'$this->Sender_Address'},".
            "'Receiver':".
            "{".
            "'Name':'$ReceiverName','Mobile':'$ReceiverMobile','ProvinceName':'$ReceiverProvinceName','CityName':'$ReceiverCityName','ExpAreaName':'$ReceiverExpAreaName','Address':'$ReceiverAddress'}".
            "}";
        $datas = [
            'EBusinessID' => $this->EBusinessID,
            'RequestType' => '1008',
            'RequestData' => urlencode($requestData),
            'DataType' => '2', //返回数据类型：2-json；
        ];
        $datas['DataSign'] = $this->encrypt($requestData, $this->AppKey);
        $result=$this->sendPost($this->ReqURL, $datas);

        //根据公司业务处理返回的信息......

        return json_decode($result,true);
    }



    /**
     *  post提交数据
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据
     * @return url响应返回的html
     */
    private function sendPost($url, $datas) {
        $temps = array();
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);
        }
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);

        return $gets;
    }

     /**
     * 电商Sign签名生成
     * @param data 内容
     * @param appkey Appkey
     * @return DataSign签名
     */
    private function encrypt($data, $appkey) {
            return urlencode(base64_encode(md5($data.$appkey)));
        }
    }